package com.nantai.jiafang.nantaijiafang.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.IConstant;
import com.nantai.jiafang.nantaijiafang.MyApplication;
import com.nantai.jiafang.nantaijiafang.R;
import com.nantai.jiafang.nantaijiafang.activity.login.Account;
import com.nantai.jiafang.nantaijiafang.activity.login.Remember;
import com.nantai.jiafang.nantaijiafang.activity.login.SjieTools;
import com.nantai.jiafang.nantaijiafang.bean.FabricBatchInfo;
import com.nantai.jiafang.nantaijiafang.bean.ProductionOrderInfo;
import com.nantai.jiafang.nantaijiafang.bean.VersionInfo;
import com.nantai.jiafang.nantaijiafang.deviceManager.Constans;
import com.nantai.jiafang.nantaijiafang.dialog.CustomAlertDialog;
import com.nantai.jiafang.nantaijiafang.fragment.Bundle_SerInfo;
import com.nantai.jiafang.nantaijiafang.utils.Tools;
import com.nantai.jiafang.nantaijiafang.view.Public;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import info.hoang8f.android.segmented.SegmentedGroup;

//deviceManager
public class LoginActivity extends AppCompatActivity {
    private EditText et_username, et_pwd;
    private Spinner company;
    private Button btn_login;
    private ProgressDialog progressDialog;
    private Context mcontext;
    private CheckBox cb_remember_pwd;
    private DbManager db;
    public static String userId="";
    private SegmentedGroup loginType;
    private int login_type;
    public List<Account> list_account;
    private ArrayList<Bundle> account;
    private static final int REQUEST_EXTERNAL_STORAGE=1;
    private static String[] PERMISSIONS_STORAGE={Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    public boolean rememberaccount;
    private int company1;

    public  void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission=ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (activity.getPackageManager().canRequestPackageInstalls()) {
                //openfile
            } else {
                // 申请权限。
                startInstallPermissionSettingActivity();
            }
        }
    }
    @RequiresApi(api = Build.VERSION_CODES.O)
    private  void startInstallPermissionSettingActivity() {
        Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES);
        startActivityForResult(intent, 10086);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 10086) {
            Toast.makeText(mcontext, "权限请求失败", Toast.LENGTH_SHORT).show();
            //openfile
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // 隐藏系统软件键盘，除非用户触发EditText
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        mcontext=LoginActivity.this;
        db=x.getDb(MyApplication.daoConfig);
        initViews();
        verifyStoragePermissions(this);
        checkUpdate();
    }

    /**
     * 检查更新
     */
    private void checkUpdate() {
        RequestParams params=new RequestParams("http://222.188.95.94:7065/AppHandler.ashx?opType=Version&platform=Android");
        x.http().post(params, new Callback.CommonCallback<String>() {

            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
//                SjieTools.showToast(mcontext, "数据同步成功");
//                anaylysisData(result);

                try {
                    JSONObject jsonObject=new JSONObject(result);
                    String versionNo=jsonObject.getString("VersionNo");
                    String updateLog=jsonObject.getString("UpdateLog");
//                    String updateLog = "XXXX\nXXXX\nXXXX\nXXXX\n";
//                    String filePath = "http://115.29.224.146/SewageService/upload/apk/test.apk";

                    //String versionname=AppUtils.getAppVersionName();
                    String versionname=getVersion(LoginActivity.this);


                    String filePath=jsonObject.getString("FilePath");
                    int v=versionNo.compareTo(versionname);
//                    updateLog = "2#3";
                    if (versionNo != null && !"".equals(versionNo) && v > 0) {
                        VersionInfo info=new VersionInfo();
                        info.setVersion_path(filePath);
                        info.setVersion_log(updateLog);
                        info.setVersion_no(versionNo);
                        versionDialog(LoginActivity.this, info);
                    }
                } catch (Exception e) {

                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                onFailure();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

//        versionDialog(LoginActivity2.this,new VersionInfo());
    }

    private void versionDialog(final Activity activity, final VersionInfo info) {
        CustomAlertDialog.Builder builder=new CustomAlertDialog.Builder(activity);
        builder.setMessage(info.getVersion_log());


        builder.setbtn_left("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (null == info.getVersion_path() || "".equals(info.getVersion_path())) {
                    Toast.makeText(LoginActivity.this, "无效的下载路径，版本更新失败", Toast.LENGTH_SHORT).show();
//                    startActivity(new Intent(LoginActivity2.this,
//                            CustomerInfoActivity.class));
                } else {
                    Intent intent=new Intent(activity, DownLoadActivity.class);
                    intent.putExtra("apkPath", "");
                    intent.putExtra("downLoadPath", info.getVersion_path());
                    activity.startActivity(intent);
                }
            }
        });

        builder.create().show();
    }

    public static String getVersion(Context mContext) {
        PackageManager packageManager=mContext.getPackageManager();
        PackageInfo packInfo=null;
        try {
            packInfo=packageManager.getPackageInfo(mContext.getPackageName(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String version=packInfo.versionName;
        if (version != null && !"".equals(version)) return version;
        else return "1.0";
    }

    private void initViews() {
        cb_remember_pwd=(CheckBox) findViewById(R.id.cb_remember_pwd);
        et_username=(EditText) findViewById(R.id.et_username);
        company=(Spinner) findViewById(R.id.company);
        et_pwd=(EditText) findViewById(R.id.et_pwd);
        btn_login=(Button) findViewById(R.id.btn_login);
        TextView mTvVersion=(TextView) findViewById(R.id.tv_version);
        //Todo 2018/5/31 版本设置待修改
        //mTvVersion.setText("版本号:" + getVersion(this));
        mTvVersion.setText("版本号:" + "3.5.5");

        progressDialog=new ProgressDialog(mcontext);
        progressDialog.setCancelable(false);
        progressDialog.setMessage("正在登陆，请稍候");
        btn_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressDialog.show();
                if (et_username.getText().toString().trim().equals("")) {
                    progressDialog.dismiss();
                    Tools.showToast(LoginActivity.this, "请输入用户名");
                } else if (et_pwd.getText().toString().trim().equals("")) {
                    progressDialog.dismiss();
                    Tools.showToast(LoginActivity.this, "请输入密码");
                } else {
                    // 登录方法
                    if (Tools.isNetAvailuable(mcontext)) {
                        progressDialog.dismiss();
                        InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                        login();
                    } else {
                        Tools.showToast(mcontext, "当前网络不可用，请检查网络");
                    }

                }
            }

        });
        getSaveLoginInfo();
//        loginType = (SegmentedGroup)findViewById(R.id.segmented2);
//        loginType.check(R.id.ml_btn);
//        loginType.setTintColor(0xFF1b7ce8);
//        loginType.setOnCheckedChangeListener(this);
    }

    //登录入口选择
//    @Override
//    public void onCheckedChanged(RadioGroup group, int checkedId) {
//        et_username.setText("");
//        et_pwd.setText("");
//
//        switch (checkedId) {
//            case R.id.ml_btn: {
//                login_type=0;
//            }
//            break;
//            case R.id.device_btn: {
//                login_type=1;
//            }
//            break;
//            default:
//                // Nothing to do
//        }
//        getSaveLoginInfo();
//    }

    //获取是否有保存登录信息
    private void getSaveLoginInfo() {
        Remember remember=SjieTools.readpassword(LoginActivity.this, IConstant.LOGINSAVEPATH);
        et_username.setText(remember.getAccount());
        et_pwd.setText(remember.getPassword());
        cb_remember_pwd.setChecked(remember.isRemember());
        String[] items=this.getResources().getStringArray(R.array.company);
        for (int i=0; i < items.length; i++) {
            if (items[i].equals(remember.getName())) {
                company.setSelection(i);
            }
        }
    }

    private void login() {
        String url;
        if (company.getSelectedItem().equals("瀚隆")) {
            Public.NAME="瀚隆";
            Constans.MIANLIAO=IConstant.HL_MIANLIAO;
            url=IConstant.HANLONG_URL_LOGIN;
            Constans.BASE_URL=Constans.HLBASE_URL;                                   //设备地址
            Constans.GETDATA=Constans.HLGETDATA;                                                  //面料利用率
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URL=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.HLURL;   //5S
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URLWORKSPACE=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.HLURLWORKSPACE;  //5S
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URL_IMG=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.HLURL_IMG;                           //5S图片
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.UPERROR=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.HLUPERROR;
            Log.e("loginlogin", "login: " + com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URL);
        } else {
            Public.NAME="南泰";
            url=IConstant.NAN1_URL_LOGIN;
            Constans.MIANLIAO=IConstant.NT_MIANLIAO;
            Constans.BASE_URL=Constans.NTBASE_URL;                                  //设备地址
            Constans.GETDATA=Constans.NTGETDATA;                                                 //面料利用率
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URL=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.NTURL; //5S
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URLWORKSPACE=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.NTURLWORKSPACE; //5S
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.URL_IMG=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.NTURL_IMG;                          //5S图片
            com.nantai.jiafang.nantaijiafang.nt5s.IConstant.UPERROR=com.nantai.jiafang.nantaijiafang.nt5s.IConstant.NTUPERROR;
        }
        RequestParams params=new RequestParams(url);
        //params.setSslSocketFactory(...); // 设置ssl
        params.addBodyParameter("loginName", et_username.getText().toString());
        params.addBodyParameter("password", et_pwd.getText().toString());
//        登录假数据
//       String result = "[{\"SystemName\":\"B:5S系统\",\"SystemLoginName\":\"admin\",\"SystemPassword\":\"123456\"},{\"SystemName\":\"A:面料利用率系统\",\"SystemLoginName\":\"admin\",\"SystemPassword\":\"123456\"}]";
//        Gson gson = new Gson();
//        list_account = gson.fromJson(result, new TypeToken<List<Account>>() {
//        }.getType());
//        登录假数据
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Data.NTLogin_Account=et_username.getText().toString();
                Gson gson=new Gson();
                list_account=gson.fromJson(result, new TypeToken<List<Account>>() {
                }.getType());
                ArrayList<Bundle_SerInfo> list_account_bundle=new ArrayList<>();
                for (Account account : list_account) {
                    Bundle_SerInfo bundle_serInfo=new Bundle_SerInfo(account.getSystemName(), account.getSystemLoginName(), account.getSystemPassword());
                    list_account_bundle.add(bundle_serInfo);
                }
//                    Toast.makeText(mcontext,result, Toast.LENGTH_SHORT).show();
                progressDialog.dismiss();
                rememberaccount=cb_remember_pwd.isChecked();
                Intent intent=new Intent();
                intent.setClass(LoginActivity.this, Login_Select.class);
                Bundle bundle=new Bundle();
                bundle.putParcelableArrayList("account", list_account_bundle);
                bundle.putBoolean("remember", rememberaccount);
                intent.putExtras(bundle);

                startActivity(intent);
                Remember account=new Remember();
                account.setAccount(et_username.getText().toString());
                account.setPassword(et_pwd.getText().toString());
                account.setRemember(cb_remember_pwd.isChecked());
                account.setName(company.getSelectedItem().toString());
                SjieTools.savepassword(LoginActivity.this, IConstant.LOGINSAVEPATH, cb_remember_pwd.isChecked(), account);
                   /* User user = new  User();
                    PreferencesUtil.setIsSave(LoginActivity.this, cb_remember_pwd.isChecked());
                    user.setUserName(et_username.getText().toString());
                    user.setPassWord(et_pwd.getText().toString());
                    user.setCompany(company.getSelectedItem().toString());
                    PreferencesUtil.saveUser(LoginActivity.this, user);*/
            }
                /*  getSupportFragmentManager().beginTransaction()
                            .addToBackStack(null)
                            .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                            .replace(R.id.container,new Login_Select())
                            .commit();*/
            //Toast.makeText(mcontext, result, Toast.LENGTH_SHORT).show();
                   /* System.out.println("返回结果：" + result);
                    String results[] = result.split(":");
                    if (results[0].equals("1")) {
                        SjieTools.showToast(mcontext, "登录成功");
                        SharedPreferences sp = getSharedPreferences(IConstant.FILE_USER, Activity.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putString(IConstant.SP_USERNAME, results[1]);
                        editor.commit();
                        User user = new  User();
                        PreferencesUtil.setIsSave(LoginActivity2.this, cb_remember_pwd.isChecked());
                        user.setUserName(et_username.getText().toString());
                        user.setPassWord(et_pwd.getText().toString());
                        user.setCompany(company.getSelectedItem().toString());
                        PreferencesUtil.saveUser(LoginActivity2.this, user);

                        userId = et_username.getText().toString();
                        progressDialog.setMessage("正在更新数据");
                        progressDialog.show();
                        updateDataFromNet();
                        //startActivity(new Intent(mcontext, MainActivity.class));

                    } else {
                        progressDialog.dismiss();
                        SjieTools.showToast(mcontext, results[1]);
                    }
                }*/

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                progressDialog.dismiss();
                Tools.showToast(mcontext, "用户名或密码错误");
                //System.out.println("出错：" + ex.getCause().toString());

            }

            @Override
            public void onCancelled(CancelledException cex) {
                progressDialog.dismiss();
                Toast.makeText(mcontext, "cancelled", Toast.LENGTH_LONG).show();
            }

            @Override
            public void onFinished() {
                progressDialog.dismiss();
            }
        });
          /*  if(login_type==1)
        {else
        {
            Map<String, String> params = new HashMap<>();
            String inputpassword = et_pwd.getText().toString();
            params.put("user_name", et_username.getText().toString());
            params.put("password", inputpassword);
            HttpClient client = new HttpClient(LoginActivity2.this);
            Call call = client.service().login(params);

            client.request(call, new ResponseHandler<User>() {
                @Override
                public void onSuccess(User user) {
                    //登陆成功，保存用户信息
                    PreferencesUtil.setIsSave(LoginActivity2.this, cb_remember_pwd.isChecked());
                    user.setUserName(et_username.getText().toString());
                    user.setPassWord(et_pwd.getText().toString());
                    user.setCompany(company.getSelectedItem().toString());
                    PreferencesUtil.saveUser(LoginActivity2.this, user);
                    //设备管理登录
                    startActivity(new Intent(LoginActivity2.this, OperateActivity.class));
                    progressDialog.dismiss();
                }

                @Override
                public void onFailure(int code, Error e) {
                    if(e.getCode().equals("CODE_USER_ERROR"))
                    {
                        progressDialog.dismiss();
                        MessagePop.ToastMessage(LoginActivity2.this,e.getMessage());
                    }else
                    {
                        progressDialog.dismiss();
                        MessagePop.ToastMessage(LoginActivity2.this, "网络异常");
                    }

                }
            });*/
    }

    //同步数据
    private void updateDataFromNet() {
        RequestParams params=new RequestParams("http://222.188.95.94:7065/PushHandler.ashx");
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                progressDialog.dismiss();
                System.out.println("返回结果：" + result);
                Tools.showToast(mcontext, "数据同步成功");
                anaylysisData(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                onFailure();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    //解析获取到的数据
    private void anaylysisData(String result) {
        Gson gson=new Gson();
        try {
            List<String> list_keys=new ArrayList<>();
            JSONObject jo=new JSONObject(result);
            Iterator it_color=jo.keys();
            while (it_color.hasNext()) {
                String key=it_color.next().toString();
                list_keys.add(key);
            }
            System.out.println("key:" + list_keys.size());
            for (int i=0; i < list_keys.size(); i++) {
                if (list_keys.get(i).contains("ML")) {
                    List<FabricBatchInfo> list_fabric=gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<FabricBatchInfo>>() {
                    }.getType());
                    for (int j=0; j < list_fabric.size(); j++) {
                        list_fabric.get(j).setIsRead("0");
                        list_fabric.get(j).setUserId(userId);
                    }
                    System.out.println("list1:" + list_fabric.size());
                    insertIntoFabricDB(list_fabric);
                } else if (list_keys.get(i).contains("SCDD")) {
                    List<ProductionOrderInfo> list_production=gson.fromJson(jo.getString(list_keys.get(i)), new TypeToken<List<ProductionOrderInfo>>() {
                    }.getType());
                    for (int j=0; j < list_production.size(); j++) {
                        list_production.get(j).setIsRead("0");
                        list_production.get(j).setUserId(userId);
                    }
                    System.out.println("list2:" + list_production.size());
                    insertIntoProductionDB(list_production);
                }
            }
            progressDialog.dismiss();
            startActivity(new Intent(mcontext, MainActivity.class));
            finish();
        } catch (JSONException e) {
            System.out.println("GSON出错");
            startActivity(new Intent(mcontext, MainActivity.class));
            finish();
        }
    }

    private void insertIntoFabricDB(List<FabricBatchInfo> list) {
        try {
            FabricBatchInfo info=list.get(0);
            List<FabricBatchInfo> list_db;
            list_db=db.selector(FabricBatchInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId", "=", userId).findAll();
            if (list_db == null || list_db.size() == 0) {
                System.out.println("插入数量1：" + list.size());
                db.save(list);
            }
        } catch (DbException e) {
            System.out.println("插入数据库出错1");
        }
    }

    private void insertIntoProductionDB(List<ProductionOrderInfo> list) {
        try {
            ProductionOrderInfo info=list.get(0);
            List<ProductionOrderInfo> list_db;
            list_db=db.selector(ProductionOrderInfo.class).where("Timestamp", "=", info.getTimestamp()).and("userId", "=", userId).findAll();
            if (list_db == null || list_db.size() == 0) {
                System.out.println("插入数量2：" + list.size());
                db.save(list);
            }
        } catch (DbException e) {
            System.out.println("插入数据库出错2");
        }
    }

    private void onFailure() {
        progressDialog.dismiss();
        Tools.showToast(mcontext, "获取更新数据失败");
//        startActivity(new Intent(mcontext, MainActivity.class));
//        finish();
    }
}
